package controller.reg;

import model.NormalUser;
import controller.login.Login;
import util.NormalUserDao;
import view.reg.RegisterFrameView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @Question Register
 * @Date 2022/12/17 14:21
 * @Solution
 */
public class Register implements ActionListener {
    RegisterFrameView registerFrameView = new RegisterFrameView();
    public void reg() {
        registerFrameView.setVisible(true);
        //添加监听
        registerFrameView.getEnter().addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String username= registerFrameView.getUsername().getText();
        String password= registerFrameView.getPassword().getText();
        String enPassword= registerFrameView.getEnPassword().getText();
        //检查信息是否合法
        if (isLegle(username,password,enPassword)) {
            //注册入数据库
            NormalUser normalUser = new NormalUser();
            normalUser.setUsername(registerFrameView.getUsername().getText());
            normalUser.setPassword(registerFrameView.getPassword().getText());
            NormalUserDao normalUserDao = new NormalUserDao();
            int ret = normalUserDao.insert(normalUser);
            if (ret == 1) {
                JOptionPane.showMessageDialog(registerFrameView.getPanel5(), "注册成功");
                registerFrameView.setVisible(false);
                Login login = new Login();
                login.login();
            } else {
                JOptionPane.showMessageDialog(registerFrameView.getPanel5(), "已有该用户名");
            }
        }
    }
    //检查信息是否合法
    public boolean isLegle(String username,String password,String enPassword) {
        if(username.equals("")) {
            JOptionPane.showMessageDialog(registerFrameView.getPanel5(), "用户名为空");
            return false;
        } else if(password.equals("")) {
            JOptionPane.showMessageDialog(registerFrameView.getPanel5(), "密码为空");
            return false;
        } else if(!password.equals(enPassword)) {
            JOptionPane.showMessageDialog(registerFrameView.getPanel5(), "两次密码不一致");
            return false;
        }
        return true;
    }
}
